package com.qianfeng.exam.service.impl;

import com.qianfeng.exam.cache.AuthorsCache;
import com.qianfeng.exam.constants.ResultCode;
import com.qianfeng.exam.event.AuthorsCacheChangeEvent;
import com.qianfeng.exam.exceptions.AddDataException;
import com.qianfeng.exam.mapper.AuthorsMapper;
import com.qianfeng.exam.pojo.Authors;
import com.qianfeng.exam.service.IAuthorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class AuthorServiceImpl implements IAuthorService {
    @Autowired
    private AuthorsMapper authorsMapper;
    @Autowired
    private AuthorsCache authorsCache;
    @Autowired//用bean的容器,发送事件,用于修改缓存中数据后,更新缓存数据
    private ApplicationContext context;
    @Autowired//一个标识,该类加了Component注解
    private AuthorsCacheChangeEvent event;
    @Override
    public void addAuthor(Authors authors) {

        //状态码太多,直接先用isnull省略了
        if (authors == null || authors.isNull()){
            throw new AddDataException("数据不能为空", ResultCode.WRITER_NAME_IS_NULL);
        }
//        if (authorsCache.getObj(authors.getAuthorid())!=null){ //没有添加过后才有id  用名字回去对象不方便
//            throw new AddDataException("作者已经存在", ResultCode.WRITER_BETWEEN_IS_NULL);
//        }
        List<Authors> allDate = authorsCache.getAllDate();
        allDate.forEach(authors1 -> {
            if (authors1.getAuthorName().equals(authors.getAuthorName())){
                throw new AddDataException("作者已经存在", ResultCode.WRITER_BETWEEN_IS_NULL);
            }
        });

        authorsMapper.addAuthor(authors);

        context.publishEvent(event);//发送事件

    }

}
